package com.air.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * HashMap 以及 CopyOnWrite
 *
 * @author shent
 */
public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, Object> hashMap = new HashMap<>(16);
        for (int i = 0; i < 12; i++) {
            hashMap.put(i + "", i);
        }
        hashMap.put("100", 100);

        //分段锁,线程安全的 map
        Map<String, Object> concurrentHashMap = new ConcurrentHashMap(16);
        //获得线程安全的hashmap
        Map<String, Object> synchronizedMap = Collections.synchronizedMap(new HashMap<>(16));

        //线程安全的 arraylist,多线程同时读写
        CopyOnWriteArrayList<String> copyOnWriteArrayList = new CopyOnWriteArrayList<>();
        //add方法 写入时加锁 复制一份新的副本Array 长度 +1 然后写入新数据
        copyOnWriteArrayList.add("1");
        copyOnWriteArrayList.get(0);
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("1");
        //自己可以用一个类继承 ArrayList
        //方案一:用读写锁 加强 ArrayList
        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        //如果读多写少,锁竞争不太激烈 方案二:CopyOnWrite  写时,空间换时间,每次复制一份相同的 Array 长度 +1 然后写入新数据
        //CopyOnWrite只保证 数据最终一致性

        //与 CopyOnWriteArrayList 插入时类似
        CopyOnWriteArraySet<String> copyOnWriteArraySet = new CopyOnWriteArraySet<>();
        copyOnWriteArraySet.add("1");
    }
}
